<?php
/**
 * Created by jinqiang on 2024/8/8 10:05.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Op;


use App\Http\Models\Mysql\SsyAllocationIpurchaseListTable;
use App\Http\Models\Mysql\SsyAllocationIpurchaseTable;
use App\Http\Models\Mysql\SsyAllocationOrderListTable;
use App\Http\Models\Mysql\SsyAllocationOrderReturnTable;
use App\Http\Models\Mysql\SsyAllocationOrderTable;
use App\Http\Models\Mysql\SsyAllocationSaleListTable;
use App\Http\Models\Mysql\SsyAllocationSaleTable;
use App\Http\Models\Mysql\SsyConfigTable;
use App\Http\Models\Mysql\SsyFeishuApprovalBindingTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Repository\FeishuRepository;
use App\Http\Repository\OmsRepository;
use App\Http\Repository\WmsRepository;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

class LendService
{
    protected $_logistics = [
        ["code" => "YTO-D", "name" => '圆通-调拨'],
        //["code" => "ZTO1", "name" => '中通-调拨'],
        ["code" => "STO-D", "name" => '申通-调拨'],
        ["code" => "JDK-D", "name" => '京东-调拨'],
        ["code" => "SF.D", "name" => '顺丰电商标快'],
        ["code" => "SF.2.D", "name" => '顺丰特快航空'],
        ["code" => "SF.COLLECT.D", "name" => '顺丰速运到付']
    ];

    public function search($param)
    {
        $conn = (new SsyAllocationOrderListTable());
        if($param['allocation_number'] ?? ""){
            $allocationNumbers = explode(",", str_replace("，", ",", $param['allocation_number']));
            $conn = $conn->whereIn('allocation_number', $allocationNumbers);
        }
        if($param['sku_code'] ?? ""){
            $skuCodes = explode(",", str_replace("，", ",", $param['sku_code']));
            $allocationOrders = (new SsyAllocationOrderTable())->whereIn('sku_code', $skuCodes)->groupBy(['allocation_number'])->get(['allocation_number'])->toArray();
            if(empty($allocationOrders)){
                return ['data' => [], 'total' => 0];
            }
            $allocationNumbers = array_column($allocationOrders, 'allocation_number');
            $conn = $conn->whereIn('allocation_number', $allocationNumbers);
        }
        if($param['adduser'] ?? ""){
            $conn = $conn->where('adduser', $param['adduser']);
        }
        if($param['from_adduser'] ?? ""){
            $conn = $conn->where('from_adduser', $param['from_adduser']);
        }
        if(isset($param['groups']) && !empty($param['groups'])){
            $conn = $conn->whereIn('groups', $param['groups']);
        }
        if(isset($param['status']) && !empty($param['status'])){
            $conn = $conn->whereIn('status', $param['status']);
        }
        if(isset($param['data_return']) && !empty($param['data_return'])){
            $conn = $conn->whereIn('data_return', $param['data_return']);
        }
        if(isset($param['is_push']) && $param['is_push'] != ""){
            $conn = $conn->where('is_push', (Int)$param['is_push']);
        }
        if(isset($param['data_status']) && $param['data_status'] != ""){
            $conn = $conn->where('data_status', (Int)$param['data_status']);
        }
        if($param['reason'] ?? ""){
            $conn = $conn->where('reason', 'like', '%'.$param['reason'].'%');
        }
        if($param['remark'] ?? ""){
            $conn = $conn->where('remark', 'like', '%'.$param['remark'].'%');
        }
        if($param['wp_address'] ?? ""){
            $conn = $conn->where('wp_address', 'like', '%'.$param['wp_address'].'%');
        }
        if($param['wp_phone'] ?? ""){
            $conn = $conn->where('wp_phone', $param['wp_phone']);
        }
        if($param['wp_user'] ?? ""){
            $conn = $conn->where('wp_user', $param['wp_user']);
        }
        if(isset($param['data_status']) && $param['data_status'] != ""){
            $conn = $conn->where('data_status', $param['data_status']);
        }
        if($param['createtime'] ?? []){
            $start = $param['createtime'][0]." 00:00:00";
            $end = $param['createtime'][1]." 23:59:59";
            $conn = $conn->whereBetween('createtime', [$start, $end]);
        }
        if($param['is_subject'] ?? ""){
            $conn = $conn->where('is_subject', $param['is_subject']);
        }
        $res = $conn->orderBy('createtime', 'desc')->paginate((Int)$param['limit'], "*", "page", (Int)$param['page'])->toArray();
        $allocationNumbers = array_column($res['data'], 'allocation_number');
        $planNumMap = [];//计划调拨数
        $actuallyNumMap = [];//实际调拨数
        $actuallyReturnNumMap = [];//实际归还数
        $ipurchaseNumMap = [];//转内购数
        $giveNumMap = [];//转赠送数
        $saleNumMap = [];//借转销售
        $skuCodeMap = [];//借出的明细规格编码
        $courierNumMap = [];//调拨单的快递单号
        $approvalIdMap = [];//飞书审批ID
        $allocationInMap = [];//调拨入的单号
        if(!empty($allocationNumbers)) {
            //获取调拨明细 & 计划数
            $allocationOrders = (new SsyAllocationOrderTable())->whereIn('allocation_number', $allocationNumbers)->get(['allocation_number', 'sku_code', 'num'])->toArray();
            foreach ($allocationOrders as $item) {
                $skuCodeMap[$item['allocation_number']][] = $item['sku_code'];
                $planNumMap[$item['allocation_number']] = ($planNumMap[$item['allocation_number']] ?? 0) + $item['num'];
            }
            //获取实际数 & 调拨快递单号
            $returnOrders = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', $allocationNumbers)
                ->get(['allocation_number','transfer_type', 'sj_num', 'courier_number'])->toArray();
            foreach ($returnOrders as $item){
                if($item['transfer_type'] == 1){
                    $actuallyNumMap[$item['allocation_number']] = ($actuallyNumMap[$item['allocation_number']] ?? 0) + $item['sj_num'];
                }
                if($item['transfer_type'] == 2){
                    $courierNumMap[$item['allocation_number']] = $item['courier_number'];
                }
            }
            //获取所有子调拨单
            $allocationReturnOrders = (new SsyAllocationOrderListTable())->whereIn('source_allocation_number', $allocationNumbers)
                ->get(['allocation_number', 'source_allocation_number'])->toArray();
            $allocationReturnMap = array_column($allocationReturnOrders,'source_allocation_number','allocation_number');
            foreach($allocationReturnMap as $allocationIn => $allocationOut){
                $allocationInMap[$allocationOut][] = $allocationIn;
            }
            //实际归还数
            $actuallyReturnOrders = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', array_keys($allocationReturnMap))->where('transfer_type', 1)
                ->get(['allocation_number', 'sj_num'])->toArray();
            foreach ($actuallyReturnOrders as $item){
                $actuallyReturnNumMap[$allocationReturnMap[$item['allocation_number']]] = ($actuallyReturnNumMap[$allocationReturnMap[$item['allocation_number']]] ?? 0)
                    + $item['sj_num'];
            }
            //转内购数
            $ipurchaseList = (new SsyAllocationIpurchaseListTable())->whereIn('jc_number', $allocationNumbers)->where('status', 1)
                ->get(['allocation_number', 'jc_number'])->toArray();
            $allocationIpurchaseMap = array_column($ipurchaseList, 'jc_number', 'allocation_number');
            $ipurchaseOrders = (new SsyAllocationIpurchaseTable())->whereIn('allocation_number', array_keys($allocationIpurchaseMap))
                ->get(['allocation_number', 'num'])->toArray();
            foreach ($ipurchaseOrders as $item){
                $ipurchaseNumMap[$allocationIpurchaseMap[$item['allocation_number']]] = ($ipurchaseNumMap[$allocationIpurchaseMap[$item['allocation_number']]] ?? 0)
                    + $item['num'];
            }
            //转赠送数
            $allocationGiveOrders = (new SsyAllocationOrderListTable())->whereIn('source_allocation_number', $allocationNumbers)->where('status', 1)->where('groups', 1)
                ->get(['allocation_number', 'source_allocation_number'])->toArray();
            $allocationGiveMap = array_column($allocationGiveOrders,'source_allocation_number','allocation_number');
            $allocationOrders = (new SsyAllocationOrderTable())->whereIn('allocation_number', array_keys($allocationGiveMap))
                ->get(['allocation_number', 'num'])->toArray();
            foreach ($allocationOrders as $item){
                $giveNumMap[$allocationGiveMap[$item['allocation_number']]] = ($giveNumMap[$allocationGiveMap[$item['allocation_number']]] ?? 0)
                    + $item['num'];
            }
            //转销售
            $saleOrders = (new SsyAllocationSaleTable())->whereIn('source_allocation_number', $allocationNumbers)
                ->get(['allocation_number','source_allocation_number', 'num'])->toArray();
            $allocationSaleNums = array_column($saleOrders, 'allocation_number');
            if(!empty($allocationSaleNums)){
                $saleList = (new SsyAllocationSaleListTable())->whereIn('allocation_number', $allocationSaleNums)->where('status', 1)->get(["allocation_number"])->toArray();
                $allocationSaleValidNums = array_column($saleList, 'allocation_number');
                foreach ($saleOrders as $item){
                    if(in_array($item['allocation_number'], $allocationSaleValidNums)){
                        $saleNumMap[$item['source_allocation_number']] = ($saleNumMap[$item['source_allocation_number']] ?? 0) + $item['num'];
                    }
                }
            }
            //飞书审批id
            $approvalList = (new SsyFeishuApprovalBindingTable())->whereIn('data_id', $allocationNumbers)->where('status', 1)
                ->get(['data_id', 'instance_code'])->toArray();
            foreach ($approvalList as $item){
                $approvalIdMap[$item['data_id']] = $item['instance_code'];
            }
        }
        foreach($res['data'] as &$item){
            $item['plan_num'] = $planNumMap[$item['allocation_number']] ?? 0;
            $item['actually_num'] = $actuallyNumMap[$item['allocation_number']] ??
                ($item['status'] == 1 && str_starts_with($item['allocation_number'], "JZS") ? $item['plan_num'] : 0);//借转送，无需推巨沃调拨计划，审核通过后为实际数
            $item['actually_return_num'] = $actuallyReturnNumMap[$item['allocation_number']] ??
                ($item['groups'] == 3 ? $item['actually_num'] : 0);//归还业务，实际数就是实际归还数
            $item['ipurchase_num'] = $ipurchaseNumMap[$item['allocation_number']] ?? 0;
            $item['give_num'] = $giveNumMap[$item['allocation_number']] ?? 0;
            $item['sale_num'] = $saleNumMap[$item['allocation_number']] ?? 0;
            $item['sku_codes'] = $skuCodeMap[$item['allocation_number']] ?? [];
            $item['courier_number'] = $courierNumMap[$item['allocation_number']] ?? "";
            $item['approval_id'] = $approvalIdMap[$item['allocation_number']] ?? "";
            $item['allocation_in_numbers'] = $allocationInMap[$item['allocation_number']] ?? [];
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function logistics()
    {
        $data = array_merge(
            (new SsyConfigTable())->where('id', 1)->first(["part_A_place","part_A_receive","part_A_receive_tel","sha_place","sha_receive","sha_receive_tel"])->toArray(),
            [
                'list' => $this->_logistics
            ]
        );
        return $data;
    }

    //取消调拨
    public function cancel($allocationNumber)
    {
        $allocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $allocationNumber)->first()->toArray();
        $subjects = array_column(config("scm.subject"), 'owner_code', 'is_subject');
        $res = WmsRepository::cancel($allocationNumber, "TRAN", $subjects[$allocationObj['is_subject']]);
        if(!$res['success']){
            return ['code' => -1, 'msg' => $res['body'], 'data' => $res];
        }
        return (new SsyAllocationOrderListTable())->updateData($allocationObj['id'], ['is_push' => 3]);
    }

    //关闭调拨计划
    public function close($allocationNumber, $remark)
    {
        $allocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $allocationNumber)->first();
        $save = [
            'data_status' => 1,
            'remark' => $allocationObj->remark." 手动完结:".$remark
        ];
        return (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => $allocationNumber], $save);
    }

    //借出列表
    public function lendList($allocationNumber)
    {
        $actuallyNumMap = [];//实际调拨数
        $actuallyReturnNumMap = [];//实际归还数
        $ipurchaseNumMap = [];//转内购数
        $giveNumMap = [];//转赠送数
        $saleNumMap = [];//借转销售
        $allocationOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->get()->toArray();
        //实际调拨数
        $returnOrders = (new SsyAllocationOrderReturnTable())->where('allocation_number', $allocationNumber)->where('transfer_type', 1)
            ->get(['sku_code', 'sj_num'])->toArray();
        foreach ($returnOrders as $item){
            $actuallyNumMap[$item['sku_code']] = ($actuallyNumMap[$item['sku_code']] ?? 0) + $item['sj_num'];
        }
        //实际归还数
        $allocationReturnOrders = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)
            ->get(['allocation_number', 'source_allocation_number'])->toArray();
        $allocationReturnMap = array_column($allocationReturnOrders,'source_allocation_number','allocation_number');
        $actuallyReturnOrders = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', array_keys($allocationReturnMap))->where('transfer_type', 1)
            ->get(['sku_code', 'sj_num'])->toArray();
        foreach ($actuallyReturnOrders as $item){
            $actuallyReturnNumMap[$item['sku_code']] = ($actuallyReturnNumMap[$item['sku_code']] ?? 0) + $item['sj_num'];
        }
        //转内购数
        $ipurchaseList = (new SsyAllocationIpurchaseListTable())->where('jc_number', $allocationNumber)->where('status', 1)->get(['allocation_number'])->toArray();
        $allocationIpurchaseNums = array_column($ipurchaseList, 'allocation_number');
        $ipurchaseOrders = (new SsyAllocationIpurchaseTable())->whereIn('allocation_number', $allocationIpurchaseNums)
            ->get(['sku_code', 'num'])->toArray();
        foreach ($ipurchaseOrders as $item){
            $ipurchaseNumMap[$item['sku_code']] = ($ipurchaseNumMap[$item['sku_code']] ?? 0) + $item['num'];
        }
        //转赠送数
        $allocationGiveList = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)->where('groups', 1)
            ->get(['allocation_number'])->toArray();
        $allocationGiveNums = array_column($allocationGiveList,'allocation_number');
        $allocationGiveOrders = (new SsyAllocationOrderTable())->whereIn('allocation_number', $allocationGiveNums)->get(['sku_code', 'num'])->toArray();
        foreach ($allocationGiveOrders as $item){
            $giveNumMap[$item['sku_code']] = ($giveNumMap[$item['sku_code']] ?? 0) + $item['num'];
        }
        //转销售
        $saleOrders = (new SsyAllocationSaleTable())->where('source_allocation_number', $allocationNumber)->get(['allocation_number', 'sku_code', 'num'])->toArray();
        $allocationSaleNums = array_column($saleOrders, 'allocation_number');
        if(!empty($allocationSaleNums)){
            $saleList = (new SsyAllocationSaleListTable())->whereIn('allocation_number', $allocationSaleNums)->where('status', 1)->get(["allocation_number"])->toArray();
            $allocationSaleValidNums = array_column($saleList, 'allocation_number');
            foreach ($saleOrders as $item){
                if(in_array($item['allocation_number'], $allocationSaleValidNums)){
                    $saleNumMap[$item['sku_code']] = ($saleNumMap[$item['sku_code']] ?? 0) + $item['num'];
                }
            }
        }
        foreach ($allocationOrders as &$item){
            $item['actually_num'] = $actuallyNumMap[$item['sku_code']] ?? 0;
            $item['actually_return_num'] = $actuallyReturnNumMap[$item['sku_code']] ?? 0;
            $item['ipurchase_num'] = $ipurchaseNumMap[$item['sku_code']] ?? 0;
            $item['give_num'] = $giveNumMap[$item['sku_code']] ?? 0;
            $item['sale_num'] = $saleNumMap[$item['sku_code']] ?? 0;
        }
        unset($item);
        return $allocationOrders;
    }

    //赠送列表
    public function giveList($allocationNumber)
    {
        $actuallyNumMap = [];
        $actuallyReturnNumMap = [];
        $allocationGiveList = (new SsyAllocationOrderListTable())->where('allocation_number', $allocationNumber)
            ->get(['status', 'allocation_number'])->toArray();
        $allocationGiveMap = array_column($allocationGiveList, 'status', 'allocation_number');
        $allocationGiveOrders = (new SsyAllocationOrderTable())->where('allocation_number', $allocationNumber)->get()->toArray();
        //实际调拨数
        $returnOrders = (new SsyAllocationOrderReturnTable())->where('allocation_number', $allocationNumber)->where('transfer_type', 1)
            ->get(['sku_code', 'sj_num'])->toArray();
        foreach ($returnOrders as $item){
            $actuallyNumMap[$item['sku_code']] = ($actuallyNumMap[$item['sku_code']] ?? 0) + $item['sj_num'];
        }
        //实际归还数
        $allocationReturnOrders = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('status', 1)
            ->get(['allocation_number'])->toArray();
        $allocationReturnNums = array_column($allocationReturnOrders,'allocation_number');
        $actuallyReturnOrders = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', $allocationReturnNums)->where('transfer_type', 1)
            ->get(['sku_code', 'sj_num'])->toArray();
        foreach ($actuallyReturnOrders as $item){
            $actuallyReturnNumMap[$item['sku_code']] = ($actuallyReturnNumMap[$item['sku_code']] ?? 0) + $item['sj_num'];
        }
        foreach($allocationGiveOrders as &$item){
            $item['actually_num'] = $actuallyNumMap[$item['sku_code']] ?? //转赠送，无需推巨沃调拨计划，审核通过后为实际数
                ($allocationGiveMap[$item['allocation_number']] == 1 && str_starts_with($item['allocation_number'], "JZS") ? $item['num'] : 0);
            $item['actually_return_num'] = $actuallyReturnNumMap[$item['sku_code']] ?? 0;
        }
        unset($item);
        return $allocationGiveOrders;
    }

    //归还列表、转归还
    public function returnList($allocationNumber, $groups)
    {
        $allocationReturnList = (new SsyAllocationOrderListTable())->where($groups == 3 ? 'allocation_number' : 'source_allocation_number', $allocationNumber)
            ->where('groups', 3)->get(['allocation_number', 'source_allocation_number', 'status', 'adduser'])->toArray();
        $allocationReturnNums = array_column($allocationReturnList, null, 'allocation_number');
        $allocationReturnOrders = (new SsyAllocationOrderTable())->whereIn('allocation_number', array_keys($allocationReturnNums))->get()->toArray();
        $actuallyReturnOrders = (new SsyAllocationOrderReturnTable())->whereIn('allocation_number', array_keys($allocationReturnNums))->where('transfer_type', 1)
            ->get(['allocation_number','sku_code', 'sj_num'])->toArray();
        $actuallyReturnNumMap = [];
        foreach ($actuallyReturnOrders as $item){
            if(isset($actuallyReturnNumMap[$item['allocation_number']][$item['sku_code']])){
                $actuallyReturnNumMap[$item['allocation_number']][$item['sku_code']] += $item['sj_num'];
            }else{
                $actuallyReturnNumMap[$item['allocation_number']][$item['sku_code']] = $item['sj_num'];
            }
        }
        foreach ($allocationReturnOrders as &$item){
            $item['adduser'] = $allocationReturnNums[$item['allocation_number']]['adduser'];
            $item['status'] = $allocationReturnNums[$item['allocation_number']]['status'];
            $item['actually_num'] = $actuallyReturnNumMap[$item['allocation_number']][$item['sku_code']] ?? 0;
        }
        unset($item);
        return $allocationReturnOrders;
    }

    //转内购
    public function ipurchaseDetail($allocationNumber)
    {
        $ipurchaseList = (new SsyAllocationIpurchaseListTable())->where('jc_number', $allocationNumber)
            ->get(['allocation_number', 'status', 'adduser'])->toArray();
        $allocationIpurchaseNums = array_column($ipurchaseList, null, 'allocation_number');
        $ipurchaseOrders = (new SsyAllocationIpurchaseTable())->whereIn('allocation_number', array_keys($allocationIpurchaseNums))->get()->toArray();
        foreach ($ipurchaseOrders as &$item){
            $item['adduser'] = $allocationIpurchaseNums[$item['allocation_number']]['adduser'];
            $item['status'] = $allocationIpurchaseNums[$item['allocation_number']]['status'];
        }
        unset($item);
        return $ipurchaseOrders;
    }

    //转赠送
    public function giveDetail($allocationNumber)
    {
        $allocationGiveList = (new SsyAllocationOrderListTable())->where('source_allocation_number', $allocationNumber)->where('groups', 1)
            ->get(['allocation_number', 'status', 'adduser'])->toArray();
        $allocationGiveNums = array_column($allocationGiveList, null, 'allocation_number');
        $allocationGiveOrders = (new SsyAllocationOrderTable())->whereIn('allocation_number', array_keys($allocationGiveNums))->get()->toArray();
        foreach ($allocationGiveOrders as &$item){
            $item['adduser'] = $allocationGiveNums[$item['allocation_number']]['adduser'];
            $item['status'] = $allocationGiveNums[$item['allocation_number']]['status'];
        }
        unset($item);
        return $allocationGiveOrders;
    }

    //转销售
    public function saleDetail($allocationNumber)
    {
        $saleOrders = (new SsyAllocationSaleTable())->where('source_allocation_number', $allocationNumber)->get()->toArray();
        if(!empty($saleOrders)){
            $allocationSaleNums = array_column($saleOrders, 'allocation_number');
            $saleList = (new SsyAllocationSaleListTable())->whereIn('allocation_number', $allocationSaleNums)->get(["allocation_number", "status", "adduser"])->toArray();
            $allocationSaleMap = array_column($saleList, null, 'allocation_number');
            foreach ($saleOrders as &$item){
                $item['adduser'] = $allocationSaleMap[$item['allocation_number']]['adduser'];
                $item['status'] = $allocationSaleMap[$item['allocation_number']]['status'];
            }
        }
        return $saleOrders;
    }

    //借赠还数量统计
    public function statistic($name)
    {
        //实际借出数量
        $lendNum = DB::table("ssy_allocation_order_list as l")
            ->rightJoin("ssy_allocation_order_return as r", 'l.allocation_number', '=', 'r.allocation_number')
            ->where('l.adduser', $name)->where('l.status', 1)->where('l.groups', 2)->where('r.transfer_type', 1)
            ->sum('r.sj_num');
        //实际归还数量
        $returnNum = DB::table("ssy_allocation_order_list as l")
            ->rightJoin("ssy_allocation_order_return as r", 'l.allocation_number', '=', 'r.allocation_number')
            ->where('l.adduser', $name)->where('l.status', 1)->where('l.groups', 3)->where('r.transfer_type', 1)
            ->sum('r.sj_num');
        //实际赠送数量
        $giveNum = DB::table("ssy_allocation_order_list as l")
            ->rightJoin("ssy_allocation_order_return as r", 'l.allocation_number', '=', 'r.allocation_number')
            ->where('l.adduser', $name)->where('l.status', 1)->where('l.groups', 1)->where('r.transfer_type', 1)
            ->sum('r.sj_num');
        //借出未归还的调拨计划数
        $unReturnNum = (new SsyAllocationOrderListTable())->where('adduser', $name)->where('status', 1)->where('data_status', 0)
            ->where('groups', 2)
            ->where('is_push', 1)
            ->whereIn('data_return', [0, 1])->count();
        return ['lend_num' => $lendNum, 'return_num' => $returnNum, 'give_num' => $giveNum, 'un_return_num' => $unReturnNum];
    }

    //归还所选
    public function returnOnly($param)
    {
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        $skuCodes = array_column($detail, 'sku_code');
        $sourceAllocationNumber = $detail[0]['allocation_number'];
        $sourceGroups = $param['reason'] == "销售商品归还" ? 4 : 2;
        $actuallyNum = (new SsyAllocationOrderReturnTable())->where('allocation_number', $sourceAllocationNumber)->whereIn('sku_code', $skuCodes)
            ->where('transfer_type', 1)->sum('sj_num');
        if($actuallyNum == 0){
            return ['code' => -1, 'msg' => '没有实际借出, 不可归还'];
        }
        if(!preg_match("/^[A-Za-z0-9]{6,18}$/is", $param['ourier_number'])){
            return ['code' => -1, 'msg' => '快递单号填写错误, 仅限一个'];
        }
        $allocationObj = (new SsyAllocationOrderListTable())->where('source_allocation_number', $sourceAllocationNumber)->where('groups', 3)->where('status', 0)->first();
        if(!empty($allocationObj)){
            return ['code' => -1, 'msg' => '当前已有归还任务，尚未完成，无法再创建归还任务'];
        }
        $user = auth()->guard("api")->user()->toArray();
        $isSubject = $param['is_subject'] ?? $user['is_subject'];
        $allocationNumber = "GH".$user['id'].date('YmdHis');
        $logistics = array_column($this->_logistics, 'name', 'code');
        DB::beginTransaction();
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "groups" => 3,
            "wp_phone" => $param['wp_phone'] ?? "",
            "remark" => $param['remark'] ?? "",
            "wp_province" => $param['wp_province'] ?? "",
            "wp_city" => $param['wp_city'] ?? "",
            "wp_area" => $param['wp_area'] ?? "",
            "wp_address" => $param['wp_address'] ?? "",
            "wp_user" => $param['wp_user'] ?? "",
            "adduser" => $user['name'],
            "transport_type" => $logistics[$param['logistics_code']] ?? $param['logistics_code'],
            "reason" => $param['reason'] ?? "",
            "logistics_company_code" => $param['logistics_code'] ?? "",
            "source_allocation_number" => $sourceAllocationNumber,
            "ourier_number" => $param['ourier_number'],
            "send_type" => $param['send_type'] ?? null,
            "is_subject" => $isSubject,
            "createtime" => date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationOrderListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //生成明细表
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        $totalNum = 0;
        $totalAmount = 0;
        $tableStr = "";
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => '计划归还数量必须大于0'];
            }
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "price" => (Double)($item['price'] ?? 0),
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationOrderTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
            $totalNum += (Int)$item['num'];
            $totalAmount += ((Int)$item['num'] * (Double)($item['price'] ?? 0));
            $tableStr .= '[{"id": "type_name","type":"input","value":"'.$jyMap[$item['sku_code']]['product_name'].'"},{"id": "sku_code","type":"input","value":"'
                .$item['sku_code'].'"},{"id":"num","type":"input","value":"'.$item['num'].'"}'
                .($sourceGroups==4?',{"id":"price","type":"input","value":"' .$item['price'].'"}':'').'],';
        }
        $tableStr = rtrim($tableStr,',');
        //发起飞书审批
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $date = date("Y-m-d\TH:i:s+H:00",time());
        $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
        $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
        $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
        $fsApprovalCode = $sourceGroups == 4 ? $subjects[$approvalSubject]['xt_approval_code'] : $subjects[$approvalSubject]['gh_approval_code'];
        $subjectLabelMap = ["kz" => "mcjyxibv-ak67q39198-0", "mz" => "mcjyxibv-nywd2n7jpj-0", "qyx" => "mcjyxibv-rwq7o4lasx-0"];
        if($sourceGroups == 4){//销售退货
            $subjectLabelMap = ["kz" => "mcjykn4y-9lphuxamkgi-0", "mz" => "mcjykn4y-ifiotecj7ql-0", "qyx" => "mcjykn4y-85ogoe8jk9l-0"];
        }
        //$fsApprovalCode = "56784612-6E64-4A57-89F4-73B28C562B9F";//测试
        //品牌字段
        $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"createtime","type":"date","value":"'.$date.'"},{"id":"allocation_number","type":"input","value":"'
                .$allocationNumber.'"},{"id":"num","type":"number","value":"'.$totalNum .'"},'
                .($sourceGroups==4 ? '{"id":"amount","type":"amount","value":"'.$totalAmount.'"},' : '')
                .'{"id":"groups","type":"input","value":"归还"},{"id": "detaillist","type": "fieldList","value": ['.$tableStr
                .']},{"id":"ourier_number","type":"input","value":"'.$allocationData['ourier_number'].'"},{"id":"wp_address","type":"textarea","value":"'
                .$allocationData['wp_user'].$allocationData['wp_phone'].$allocationData['wp_province'].$allocationData['wp_city'].$allocationData['wp_area']
                .$allocationData['wp_address']. '"},{"id":"remark","type":"textarea","value":"'.$allocationData['remark'].'"}]'
        ];
        $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
        if($res['code'] != '0'){
            DB::rollBack();
            return ['code' => -1, 'msg' => '创建归还,失败!'.($res['msg']??""), 'data' => $res];
        }
        $createRes = (new SsyFeishuApprovalBindingTable())->createData([
            "instance_code" => $res['data']['instance_code'],
            "data_id" => $allocationNumber,
            "types" => 2,
            "createtime" => date('Y-m-d H:i:s')
        ]);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => $allocationNumber], ['status' => 0]);
        DB::commit();
        return $createRes;
    }

    //归还所选--系统处理
    public function returnSys($param)
    {
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        $skuCodes = array_column($detail, 'sku_code');
        $sourceAllocationNumber = $detail[0]['allocation_number'];
        $actuallyNum = (new SsyAllocationOrderReturnTable())->where('allocation_number', $sourceAllocationNumber)->whereIn('sku_code', $skuCodes)
            ->where('transfer_type', 1)->sum('sj_num');
        if($actuallyNum == 0){
            return ['code' => -1, 'msg' => '没有实际借出, 不可归还'];
        }
        if(!preg_match("/^[A-Za-z0-9]{6,18}$/is", $param['ourier_number'])){
            return ['code' => -1, 'msg' => '快递单号填写错误, 仅限一个'];
        }
        $allocationObj = (new SsyAllocationOrderListTable())->where('source_allocation_number', $sourceAllocationNumber)->where('groups', 3)->where('status', 0)->first();
        if(!empty($allocationObj)){
            return ['code' => -1, 'msg' => '当前已有归还任务，尚未完成，无法再创建归还任务'];
        }
        $sourceAllocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $sourceAllocationNumber)->first(['adduser', 'is_subject'])->toArray();
        $user = auth()->guard("api")->user()->toArray();
        $isSubject = $sourceAllocationObj['is_subject'];
        $allocationNumber = "GH".$user['id'].date('YmdHis');
        $logistics = array_column($this->_logistics, 'name', 'code');
        DB::beginTransaction();
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "groups" => 3,
            "status" => 1,
            "wp_phone" => $param['wp_phone'] ?? "",
            "remark" => $param['remark'] ?? "",
            "wp_province" => $param['wp_province'] ?? "",
            "wp_city" => $param['wp_city'] ?? "",
            "wp_area" => $param['wp_area'] ?? "",
            "wp_address" => $param['wp_address'] ?? "",
            "wp_user" => $param['wp_user'] ?? "",
            "adduser" => $sourceAllocationObj['adduser'],
            "transport_type" => $logistics[$param['logistics_code']] ?? $param['logistics_code'],
            "reason" => $param['reason'] ?? "",
            "logistics_company_code" => $param['logistics_code'] ?? "",
            "source_allocation_number" => $sourceAllocationNumber,
            "ourier_number" => $param['ourier_number'],
            "send_type" => $param['send_type'] ?? null,
            "is_subject" => $isSubject,
            "data_return" => 2,
            "createtime" => date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationOrderListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //生成归还明细表  & 归还回写单据
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => '计划归还数量必须大于0'];
            }
            //归还明细表
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "is_return" => 2,
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationOrderTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
            //归还回写单据
            $data = [
                "allocation_number" => $allocationNumber,
                "transfer_type" => 1,
                "sku_code" => $item['sku_code'],
                "sj_num" => (Int)$item['num'],
                "db_num" => (Int)$item['num'],
                "order_type" => "TRANIN",
                "goods_owner" => "SSY",
                "from_whcode" => "DBJ",
                "target_whcode" => "XTC",
                "operator" => "无来源",
                "createtime" => date("Y-m-d H:i:s")
            ];
            $allocationNumbers[$item['allocation_number']] = $param['courier_number'] ?? "";
            (new SsyAllocationOrderReturnTable())->createData($data);
        }
        DB::commit();
        return ['code' => 0];
    }

    //赠送转归还
    public function returnGive($param)
    {
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        $skuCodes = array_column($detail, 'sku_code');
        $sourceAllocationNumber = $detail[0]['allocation_number'];
        $actuallyNum = (new SsyAllocationOrderReturnTable())->where('allocation_number', $sourceAllocationNumber)->whereIn('sku_code', $skuCodes)
            ->where('transfer_type', 1)->sum('sj_num');
        if($actuallyNum == 0){
            return ['code' => -1, 'msg' => '没有实际赠送, 不可归还'];
        }
        $allocationObj = (new SsyAllocationOrderListTable())->where('source_allocation_number', $sourceAllocationNumber)->where('groups', 3)->where('status', 0)->first();
        if(!empty($allocationObj)){
            return ['code' => -1, 'msg' => '当前已有归还任务， 尚未完成， 无法再创建归还任务'];
        }
        $user = auth()->guard("api")->user()->toArray();
        $isSubject = $param['is_subject'] ?? $user['is_subject'];
        $allocationNumber = "SZH".$user['id'].date('YmdHis');
        $logistics = array_column($this->_logistics, 'name', 'code');
        DB::beginTransaction();
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "groups" => 3,
            "wp_phone" => $param['wp_phone'] ?? "",
            "remark" => $param['remark'] ?? "",
            "wp_province" => $param['wp_province'] ?? "",
            "wp_city" => $param['wp_city'] ?? "",
            "wp_area" => $param['wp_area'] ?? "",
            "wp_address" => $param['wp_address'] ?? "",
            "wp_user" => $param['wp_user'] ?? "",
            "adduser" => $user['name'],
            "transport_type" => $logistics[$param['logistics_code']] ?? $param['logistics_code'],
            "reason" => $param['reason'] ?? "",
            "logistics_company_code" => $param['logistics_code'] ?? "",
            "source_allocation_number" => $sourceAllocationNumber,
            "ourier_number" => $param['ourier_number'] ?? "",
            "send_type" => $param['send_type'] ?? null,
            "is_subject" => $isSubject,
            "createtime" => date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationOrderListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //生成明细表
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        $totalNum = 0;
        $tableStr = "";
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => '计划归还数量必须大于0'];
            }
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationOrderTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
            $totalNum += (Int)$item['num'];
            $tableStr .= '[{"id": "allocation_number","type":"input","value":"'.$allocationNumber.'"},{"id": "type_name","type":"input","value":"'
                .$jyMap[$item['sku_code']]['product_name'].'"},{"id": "sku_code","type":"input","value":"'
                .$item['sku_code'].'"},{"id":"num","type":"input","value":"'.$item['num'].'"}],';
        }
        $tableStr = rtrim($tableStr,',');
        //发起飞书审批
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $date = date("Y-m-d\TH:i:s+H:00",time());
        $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
        $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
        $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$approvalSubject]['szh_approval_code'];
        //$fsApprovalCode = "F77EDC50-E87C-4E25-B32A-50F62D583647";//测试
        $subjectLabelMap = ["kz" => "mck31p21-8pc012v47k3-0", "mz" => "mck31p21-tpls7wngass-0", "qyx" => "mck31p21-wmq6xrgm67p-0"];
        //品牌字段
        $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"createtime","type":"date","value":"'.$date.'"},{"id":"source_allocation_number","type":"input","value":"'
                .$sourceAllocationNumber.'"},{"id":"reason","type":"textarea","value":"'.$allocationData['reason'].'"},{"id":"num","type":"number","value":"'.$totalNum
                .'"},{"id":"groups","type":"input","value":"赠送转归还"},{"id": "detaillist","type": "fieldList","value": ['
                .$tableStr.']},{"id": "ourier_number","type": "input","value": "'.$allocationData['ourier_number']
                .'"},{"id": "wp_address","type": "textarea","value": "'.$allocationData['wp_user'].$allocationData['wp_phone'].$allocationData['wp_province']
                .$allocationData['wp_city'].$allocationData['wp_area'].$allocationData['wp_address'].'"},{"id": "remark","type": "textarea","value": "'
                .$allocationData['remark'].'"}]'
        ];
        $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
        if($res['code'] != '0'){
            DB::rollBack();
            return ['code' => -1, 'msg' => '创建赠转归还,失败!'.($res['msg']??""), 'data' => $res];
        }
        $createRes = (new SsyFeishuApprovalBindingTable())->createData([
            "instance_code" => $res['data']['instance_code'],
            "data_id" => $allocationNumber,
            "types" => 8,
            "createtime" => date('Y-m-d H:i:s')
        ]);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => $allocationNumber], ['status' => 0]);
        DB::commit();
        return $createRes;
    }

    //借出转赠送
    public function giveLend($param)
    {
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        $skuCodes = array_column($detail, 'sku_code');
        $sourceAllocationNumber = $param['allocation_number'];
        $actuallyNum = (new SsyAllocationOrderReturnTable())->where('allocation_number', $sourceAllocationNumber)->whereIn('sku_code', $skuCodes)
            ->where('transfer_type', 1)->sum('sj_num');
        if($actuallyNum == 0){
            return ['code' => -1, 'msg' => '没有实际借出, 不可赠送'];
        }
        $allocationObj = (new SsyAllocationOrderListTable())->where('source_allocation_number', $sourceAllocationNumber)->where('groups', 1)->where('status', 0)->first();
        if(!empty($allocationObj)){
            return ['code' => -1, 'msg' => '当前已有赠送任务， 尚未完成， 无法再创建赠送任务'];
        }
        $user = auth()->guard("api")->user()->toArray();
        $isSubject = $param['is_subject'] ?? $user['is_subject'];
        $allocationNumber = "JZS".$user['id'].date('YmdHis');
        $allocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $sourceAllocationNumber)->first()->toArray();
        DB::beginTransaction();
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "groups" => 1,
            "wp_phone" => $allocationObj['wp_phone'],
            "remark" => $allocationObj['remark'],//
            "wp_province" => $allocationObj['wp_province'],
            "wp_city" => $allocationObj['wp_city'],
            "wp_area" => $allocationObj['wp_area'],
            "wp_address" => $allocationObj['wp_address'],
            "wp_user" => $allocationObj['wp_user'],
            "adduser" => $user['name'],
            "transport_type" => $allocationObj['transport_type'],
            "reason" => $param['reason'],
            "logistics_company_code" => $allocationObj['logistics_company_code'],
            "source_allocation_number" => $sourceAllocationNumber,
            "ourier_number" => $allocationObj['ourier_number'],
            "send_type" => $allocationObj['send_type'],
            "is_subject" => $isSubject,
            "createtime"=>date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationOrderListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //生成明细表
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        $totalNum = 0;
        $tableStr = "";
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => '计划归还数量必须大于0'];
            }
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationOrderTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
            $totalNum += (Int)$item['num'];
            $tableStr .= '[{"id": "allocation_number","type":"input","value":"'.$allocationNumber.'"},{"id": "type_name","type":"input","value":"'
                .$jyMap[$item['sku_code']]['product_name'].'"},{"id": "sku_code","type":"input","value":"'
                .$item['sku_code'].'"},{"id":"num","type":"input","value":"'.$item['num'].'"}],';
        }
        $tableStr = rtrim($tableStr,',');
        //发起飞书审批
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $date = date("Y-m-d\TH:i:s+H:00",time());
        $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
        $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
        $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$approvalSubject]['jzs_approval_code'];
        $subjectLabelMap = ["kz" => "mck3qn1k-vtb8lfmvb98-0", "mz" => "mck3qn1k-n1ra03echrp-0", "qyx" => "mck3qn1k-jgytkzf4x4g-0"];
        //$fsApprovalCode = "08B78A73-5B05-4925-97C6-F268A682DFC2";//测试
        //品牌字段
        $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"createtime","type":"date","value":"'.$date.'"},{"id":"source_allocation_number","type":"input","value":"'
                .$sourceAllocationNumber.'"},{"id":"reason","type":"textarea","value":"'.$param['reason'].'"},{"id":"num","type":"number","value":"'.$totalNum
                .'"},{"id":"groups","type":"input","value":"借出转赠送"},{"id": "detaillist","type": "fieldList","value": ['.$tableStr.']}]'
        ];
        $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
        if($res['code'] != '0'){
            DB::rollBack();
            return ['code' => -1, 'msg' => '创建借转赠送,失败!'.($res['msg']??""), 'data' => $res];
        }
        $createRes = (new SsyFeishuApprovalBindingTable())->createData([
            "instance_code" => $res['data']['instance_code'],
            "data_id" => $allocationNumber,
            "types" => 7,
            "createtime" => date('Y-m-d H:i:s')
        ]);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => $allocationNumber], ['status' => 0]);
        DB::commit();
        return $createRes;
    }

    //借出转赠送--系统处理
    public function giveLendSys($param)
    {
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        $skuCodes = array_column($detail, 'sku_code');
        $sourceAllocationNumber = $param['allocation_number'];
        $actuallyNum = (new SsyAllocationOrderReturnTable())->where('allocation_number', $sourceAllocationNumber)->whereIn('sku_code', $skuCodes)
            ->where('transfer_type', 1)->sum('sj_num');
        if($actuallyNum == 0){
            return ['code' => -1, 'msg' => '没有实际借出, 不可赠送'];
        }
        $allocationObj = (new SsyAllocationOrderListTable())->where('source_allocation_number', $sourceAllocationNumber)->where('groups', 1)->where('status', 0)->first();
        if(!empty($allocationObj)){
            return ['code' => -1, 'msg' => '当前已有赠送任务， 尚未完成， 无法再创建赠送任务'];
        }
        $sourceAllocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $sourceAllocationNumber)->first()->toArray();
        $isSubject = $sourceAllocationObj['is_subject'];
        $user = auth()->guard("api")->user()->toArray();
        $allocationNumber = "JZS".$user['id'].date('YmdHis');
        DB::beginTransaction();
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "groups" => 1,
            "status" => 1,
            "wp_phone" => $sourceAllocationObj['wp_phone'],
            "remark" => $param['remark'],
            "wp_province" => $sourceAllocationObj['wp_province'],
            "wp_city" => $sourceAllocationObj['wp_city'],
            "wp_area" => $sourceAllocationObj['wp_area'],
            "wp_address" => $sourceAllocationObj['wp_address'],
            "wp_user" => $sourceAllocationObj['wp_user'],
            "adduser" => $sourceAllocationObj['adduser'],
            "transport_type" => $sourceAllocationObj['transport_type'],
            "reason" => $param['reason'],
            "logistics_company_code" => $sourceAllocationObj['logistics_company_code'],
            "source_allocation_number" => $sourceAllocationNumber,
            "ourier_number" => $sourceAllocationObj['ourier_number'],
            "send_type" => $sourceAllocationObj['send_type'],
            "is_subject" => $isSubject,
            "createtime"=>date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationOrderListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //生成赠送明细表
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => '计划归还数量必须大于0'];
            }
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationOrderTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
        }
        DB::commit();
        return ['code' => 0];
    }

    //借出转内购
    public function ipurchase($param)
    {
        $user = auth()->guard("api")->user()->toArray();
        $isSubject = $param['is_subject'] ?? $user['is_subject'];
        $detail = $param['detail'] ?? [];
        if(empty($detail)){
            return ['code' => -1, 'msg' => '请提交归还任务明细'];
        }
        //同一账号每月只能购买一次
        $exist = (new SsyAllocationIpurchaseListTable())->where('adduser', $user['name'])->where('status', [0, 1])->where('is_subject', $isSubject)
            ->whereBetween('createtime', [date('Y-m-01 00:00:00'), date('Y-m-t 23:59:59')])->exists();
        if($exist){
            return ['code' => -1, '同一账号每月只能购买一次噢！！！'];
        }
        $skuCodes = array_column($detail, 'sku_code');
        $sourceAllocationNumber = $param['allocation_number'];
        $allocationNumber = "ZNG".$user['id'].date('YmdHis');
        $discount = (Double)$param['discount'] / 10;
        $allocationObj = (new SsyAllocationOrderListTable())->where('allocation_number', $sourceAllocationNumber)->first()->toArray();
        //生成明细表
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        $totalNum = 0;
        $totalPrice = 0;
        $tableStr = "";
        DB::beginTransaction();
        foreach ($detail as $item){
            if((Int)$item['num'] <= 0 || empty($item['price'])){
                DB::rollBack();
                return ['code' => -1, 'msg' => '数量或价格 错误'];
            }
            $orderData = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => (Int)$item['num'],
                "price" => (Double)$item['price'],
                "types" => 1,//1 借出转内购 0 普通内购
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationIpurchaseTable())->createData($orderData);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
            $totalNum += (Int)$item['num'];
            $totalPrice += (Int)$item['num'] * (Double)$item['price'];
            $tableStr .= '[{"id": "type_name","type":"input","value":"'.$jyMap[$item['sku_code']]['product_name'].'"},{"id": "sku_code","type":"input","value":"'
                .$item['sku_code'].'"},{"id":"num","type":"input","value":"'.$item['num'].'"},{"id":"price","type":"input","value":"'.$item['price'].'"}],';
        }
        $tableStr = rtrim($tableStr,',');
        $discountPrice = round($totalPrice*$discount, 2);
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "wp_phone" => $allocationObj['wp_phone'],
            "wp_province" => $allocationObj['wp_province'],
            "wp_city" => $allocationObj['wp_city'],
            "wp_area" => $allocationObj['wp_area'],
            "wp_address" => $allocationObj['wp_address'],
            "wp_user" => $allocationObj['wp_user'],
            "adduser" => $user['name'],
            "total_num" => $totalNum,
            "total_price" => $totalPrice,
            "images" => $param['img'],
            "types" => 1,//1 借出转内购 0 普通内购
            "jc_number" => $sourceAllocationNumber,
            "is_subject" => $isSubject,
            "discount" => $discount,
            "discount_amount" => $discountPrice,
            "createtime"=>date("Y-m-d H:i:s",time())
        ];
        $res = (new SsyAllocationIpurchaseListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        //发起飞书审批
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $date = date("Y-m-d\TH:i:s+H:00",time());
        $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
        $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
        $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$approvalSubject]['zng_approval_code'];
        //$fsApprovalCode = "BC9D00C6-A1E5-480B-AB3C-C05A6FE2B709";//内部测试
        $subjectLabelMap = ["kz" => "mck4ffhj-o3j5bbnfzn-0", "mz" => "mck4ffhj-9xuo5nmmnjv-0", "qyx" => "mck4ffhj-irckuxg701-0"];
        //品牌字段
        $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"createtime","type":"date","value":"'.$date.'"},{"id":"allocation_number","type":"input","value":"'.$allocationNumber
                .'"},{"id":"total_num","type":"input","value":"'.$totalNum.'"},{"id":"total_price","type":"input","value":"'.$totalPrice
                .'"},{"id":"discount","type":"input","value":"'.$discount.'"},{"id":"discount_total_price","type":"input","value":"'.$discountPrice
                .'"},{"id": "detaillist","type": "fieldList","value": ['.$tableStr.']},{"id":"wp_address","type":"textarea","value":"'
                .$allocationObj['wp_user'].$allocationObj['wp_phone'].$allocationObj['wp_province'].$allocationObj['wp_city'].$allocationObj['wp_area']
                .$allocationObj['wp_address'].'"},{"id":"remark","type":"textarea","value":"'.$param['img'].'"},{"id":"images","type":"image","value":["'.$param['img'].'"]}]'
        ];
        $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
        if($res['code'] != '0'){
            DB::rollBack();
            return ['code' => -1, 'msg' => '创建借转内购,失败!'.($res['msg']??""), 'data' => $res];
        }
        $createRes = (new SsyFeishuApprovalBindingTable())->createData([
            "instance_code" => $res['data']['instance_code'],
            "data_id" => $allocationNumber,
            "types" => 4,
            "createtime" => date('Y-m-d H:i:s')
        ]);
        if($createRes['code'] !== 0){
            DB::rollBack();
            return $createRes;
        }
        DB::commit();
        return $createRes;
    }

    //创建借出、赠送调拨计划
    public function createPlan($param)
    {
        $user = auth()->guard("api")->user()->toArray();
        $groups = $param['groups'];
        $logistics = array_column($this->_logistics, 'name', 'code');
        $skuCodes = array_column($param['detail'], 'sku_code');
        $subject = array_column(config("scm.subject"), 'virtual_warehouse_code', 'is_subject');
        if(!in_array($param['courier_type'], ["无需快递", "上门取货"])) {
            if (!preg_match("/^SF/is", $param['logistics_code']) && array_sum(array_column($param['detail'], 'num')) > 100) {
                return ['code' => -1, 'msg' => '操作数量太大，仓库包裹超重，请分批次处理(限制100件内)！可以尝试顺丰噢！'];
            }
        }
        //获取巨益可销售数据
        $omsRes = OmsRepository::searchNum($subject[$user['is_subject']], $skuCodes);
        $omsList = $omsRes['stockInfoList'] ?? [];
        $omsSellableQuantity =  array_column($omsList, "sellableQuantity", "skuCode");
        $preMap = [1 => "ZS", 2 => "JC", 4 => "XS"];//单据类型
        $allocationNumber = $preMap[$groups].$user['id'].date('YmdHis');
        DB::beginTransaction();
        //生成调拨表
        $allocationData = [
            "allocation_number" => $allocationNumber,
            "groups" => $groups,
            "wp_phone" => $param['wp_phone'],
            "remark" => str_replace("\n", ",", $param['remark']),
            "wp_province" => $param['wp_province'] ?? "",
            "wp_city" => $param['wp_city'] ?? "",
            "wp_area" => $param['wp_area'] ?? "",
            "wp_address" => $param['wp_address'] ?? "",
            "wp_user" => $param['wp_user'],
            "adduser" => $user['name'],
            "transport_type" => $logistics[$param['logistics_code']] ?? "",
            "reason" => str_replace("\n", ",", $param['reason']),
            "logistics_company_code" => $param['logistics_code'],
            "send_type" => $param['send_type'],
            "date" => $param['send_type'] == 1 ? $param['send_date'] : null,
            "is_subject" => $user['is_subject'],
            "createtime" => date("Y-m-d H:i:s")
        ];
        $res = (new SsyAllocationOrderListTable())->createData($allocationData);
        if($res['code'] !== 0){
            DB::rollBack();
            return $res;
        }
        $jyList = (new SsyJyProductListTable())->whereIn('product_code', $skuCodes)->get(["type_no","product_code","product_name","img"])->toArray();
        $jyMap = array_column($jyList, null, 'product_code');
        //生成详细
        foreach ($param['detail'] as $item){
            $num = (Int)$item['num'];
            if($num <= 0){
                DB::rollBack();
                return ['code' => -1, 'msg' => $item['sku_code']." 数量错误"];
            }
            //立即发货：预留3件判断，防止超发
            if($param['send_type'] != 1){
                $allocationPlanNum = Cache::get("ALLOCATION_LEND_".$user['name']."_".$item['sku_code']);
                Cache::forget("ALLOCATION_LEND_".$user['name']."_".$item['sku_code']);
                //预留解除
                $relieve = !empty($allocationPlanNum) && $allocationPlanNum == $num ? true : false;
                if($num > $omsSellableQuantity[$item['sku_code']] - 3 && !$relieve){
                    DB::rollBack();
                    return ['code' => -1, 'msg' => $item['sku_code']." 不可超出可销数！"];
                }
            }
            $order = [
                "allocation_number" => $allocationNumber,
                "type_name" => $jyMap[$item['sku_code']]['product_name'],
                "type_no" => $jyMap[$item['sku_code']]['type_no'],
                "img" => $jyMap[$item['sku_code']]['img'],
                "sku_code" => $item['sku_code'],
                "num" => $num,
                "price" => $item['price'] ?? 0,
                "createtime" => date("Y-m-d H:i:s")
            ];
            $res = (new SsyAllocationOrderTable())->createData($order);
            if($res['code'] !== 0){
                DB::rollBack();
                return $res;
            }
        }
        DB::commit();
        return ['code' => 0];
    }

    //借出、赠送发起审批
    public function approval($param)
    {
        $groups = $param['groups'];
        $title = $groups == 4 ? "销售" : ($groups == 2 ? "借出" : "赠送");
        $allocationNumbers = $param['allocation_number'];
        $allocationList = (new SsyAllocationOrderListTable())->whereIn('allocation_number', $allocationNumbers)
            ->get(["allocation_number", "wp_user", "wp_phone", "wp_province", "wp_city", "wp_area", "wp_address", "remark", "reason"])->toArray();
        $allocationOrders = (new SsyAllocationOrderTable())->whereIn('allocation_number', $allocationNumbers)
            ->get(["allocation_number", "sku_code", "type_name", "num", "price"])->toArray();
        $allocationOrderMap = [];
        foreach ($allocationOrders as $item){
            $allocationOrderMap[$item['allocation_number']][] = $item;
        }
        $reason = $allocationList[0]['reason'];
        $logisticsInfo = "";//物流信息
        $detailInfo = "";//单据明细
        $totalNum = 0;
        $totalAmount = 0;
        foreach($allocationList as $item){
            foreach($allocationOrderMap[$item['allocation_number']] as $order){
                $totalNum += (Int)$order['num'];
                $totalAmount += ((Int)$order['num'] * (Double)($order['price'] ?? 0));
                $detailInfo .= '[{"id": "allocation_number","type":"input","value":"'.$order['allocation_number'].'"},{"id": "type_name","type":"input","value":"'
                    .$order['type_name'].'"},{"id": "sku_code","type":"input","value":"'.$order['sku_code'].'"},{"id":"num","type":"input","value":"'
                    .$order['num'].'"}'.($groups==4?',{"id":"price","type":"input","value":"' .$order['price'].'"}':'').'],';
            }
            $logisticsInfo .= '[{"id": "allocation_number","type":"input","value":"'.$item['allocation_number'].'"},{"id":"wp_address","type":"textarea","value":"'
                .$item['wp_user'].$item['wp_phone'].$item['wp_province'].$item['wp_city'].$item['wp_area']
                .$item['wp_address'].'"},{"id":"remark","type":"textarea","value":"'.$item['remark'].'"}],';
        }
        $detailInfo = rtrim($detailInfo,',');
        $logisticsInfo = rtrim($logisticsInfo,',');
        //发起飞书审批
        $date=date("Y-m-d\TH:i:s+H:00",time());
        $user = auth()->guard("api")->user()->toArray();
        $subjects = $groups == 4 ? array_column(config("scm.subject"), 'xs_approval_code', 'is_subject') :
            array_column(config("scm.subject"), 'jz_approval_code', 'is_subject');
        $isSubject = in_array($user['is_subject'], ['kz', 'qyx']) ? 'kz' : $user['is_subject'];
        $fsUserId = $user[$isSubject.'_feishu_user_id'];
        $fsOpenId = $user[$isSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$isSubject];
        $subjectLabelMap = ["kz" => "mcjwpe2k-939a9vbu4b7-0", "mz" => "mcjwpe2k-3c5xd0indcj-0", "qyx" => "mcjwpe2k-4qid4re5z2d-0"];
        if($groups == 4){//线下销售
            $subjectLabelMap = ["kz" => "mcjx5jk3-k7xghh9nvlm-0", "mz" => "mcjx5jk3-f00rm6v9ysg-0", "qyx" => "mcjx5jk3-82yma1dn4x6-0"];
        }
        //$fsApprovalCode = "4642FD93-5CB1-49D3-95B2-7861A529B0F2";//测试
        //$subjectLabelMap = ["kz" => "mcjwbm98-h2l1t96d3v-0", "mz" => "mcjwbm98-2brg0he2zby-0", "qyx" => "mcjwbm98-xavmxtbnsx-0"];//测试
        //品牌字段
        $brandStr = $isSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$user['is_subject']].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"createtime","type":"date","value":"'.$date.'"},{"id":"reason","type":"textarea","value":"'
                .$reason.'"},{"id":"num","type":"number","value":"'.$totalNum.'"},'
                .($groups==4 ? '{"id":"amount","type":"amount","value":"'.$totalAmount.'"},' : '').'{"id":"groups","type":"input","value":"'
                .$title.'"},{"id": "detaillist","type": "fieldList","value": ['.$detailInfo.']},{"id": "detaillist_er","type": "fieldList","value": ['
                .$logisticsInfo.']}]'
        ];
        $res = (new FeishuRepository($isSubject))->createApproval($postData);
        if($res['code'] != '0'){
            return ['code' => -1, 'msg' => $title.': 创建审批失败!'.($res['msg']??""), 'data' => $res];
        }
        //如果是重发审批，需作废之前的绑定
        (new SsyFeishuApprovalBindingTable())->updateDataWhere(['data_id' => ['in' => $allocationNumbers]], ['status' => 0]);
        //创建审批记录
        foreach($allocationNumbers as $allocationNumber){
            (new SsyFeishuApprovalBindingTable())->createData([
                "instance_code" => $res['data']['instance_code'],
                "data_id" => $allocationNumber,
                "types" => $groups == 4 ? 14 : ($groups == 2 ? 1 : 3),//1借出 3赠送 14销售
                "createtime" => date('Y-m-d H:i:s')
            ]);
        }
        (new SsyAllocationOrderListTable())->updateDataWhere(['allocation_number' => ['in' => $allocationNumbers]], ['status' => 0]);
        return ['code' => 0];
    }

    public function handover($param)
    {
        list($fromUser, $toUser, $isGive, $isOk) = [$param['fromUser'], $param['toUser'], isset($param['is_give']) && $param['is_give'] == "true" ? 1 : 0, (Int)$param['is_ok']];
        $groups = $isGive ? [1, 2] : [2];
        //正式转交操作
        if($isOk){
            $where = [
                'groups' => ['in' => $groups],
                'data_return' => ['in' => [0, 1]],
                'adduser' => $fromUser,
                'status' => ['in' => [0, 1]],
                'data_status' => 0
            ];
            return (new SsyAllocationOrderListTable())->updateDataWhere($where, ['adduser' => $toUser, 'from_adduser' => $fromUser]);
        }else{//二次确认转交的数据量
            $num = (new SsyAllocationOrderListTable())->whereIn('groups', $groups)->whereIn('data_return', [0, 1])->where('adduser', $fromUser)->whereIn('status', [0, 1])
                ->where('data_status', 0)->count();
            return ['code' => 0, 'data' => $num];
        }
    }

    //审批进度
    public function approvalProcess($param)
    {
        //获取审批数据
        if(isset($param['type']) && $param['type'] == 'JZX'){
            $obj = (new SsyAllocationSaleListTable())->where('id', (Int)$param['id'])->first()->toArray();
        }elseif (isset($param['type']) && $param['type'] == 'NG'){
            $obj = (new SsyAllocationIpurchaseListTable())->where('id', (Int)$param['id'])->first()->toArray();
        }else{
            $obj = (new SsyAllocationOrderListTable())->where('id', (Int)$param['id'])->first()->toArray();
        }
        //获取审批流程 合并融合 需要做时间判断，之前的还是各自的飞书主体
        $isSubject = $obj['is_subject'];
        if($obj['createtime'] >= '2025-07-01' && in_array($obj['is_subject'], ['kz', 'qyx'])){
            $isSubject = 'kz';
        }
        $flow = (new FeishuRepository($isSubject))->getFlow($param['run_id']);
        return ['flow' => $flow, 'data' => $obj];
    }
}
